package com.threaddemo8;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo2 {
    static int readCount = 0;
    static int writeCount = 0;
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    public static void main(String[] args) {
        read();
        System.out.println("=====================");
        write();
    }

    public static void read(){
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    readLock.lock();
                    readCount++;
                    System.out.println("read = " + readCount);
                    readLock.unlock();
                }
            }).start();
        }
    }

    public static void write(){
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    writeLock.lock();
                    writeCount++;
                    System.out.println("write = " + writeCount);
                    writeLock.unlock();
                }
            }).start();
        }
    }

}
